<template>
  <div class="list-operations">
    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><Plus /></el-icon> 添加列表元素</span>
        </div>
      </template>
      <el-form :model="lpushForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="lpushForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item label="值">
          <el-input v-model="lpushForm.value" placeholder="请输入值" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLPush" :icon="Plus">左侧添加</el-button>
          <el-button type="success" @click="handleRPush" :icon="Plus">右侧添加</el-button>
          <el-button @click="resetPushForm" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><Remove /></el-icon> 移除列表元素</span>
        </div>
      </template>
      <el-form :model="lpopForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="lpopForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="handleLPop" :icon="Remove">左侧移除</el-button>
          <el-button type="warning" @click="handleRPop" :icon="Remove">右侧移除</el-button>
          <el-button @click="resetPopForm" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
      <div v-if="popResult !== ''" class="result-box">
        <div class="result-header">
          <h4>结果:</h4>
          <el-button type="text" @click="copyPopResult" :icon="CopyDocument">复制</el-button>
        </div>
        <el-alert
          v-if="popResult === null"
          title="列表为空或不存在"
          type="warning"
          :closable="false"
          show-icon
        />
        <pre v-else>{{ popResult }}</pre>
      </div>
    </el-card>

    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><List /></el-icon> 获取列表范围</span>
        </div>
      </template>
      <el-form :model="lrangeForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="lrangeForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item label="起始索引">
          <el-input-number v-model="lrangeForm.start" :min="0" :step="1" />
        </el-form-item>
        <el-form-item label="结束索引">
          <el-input-number v-model="lrangeForm.end" :min="-1" :step="1" />
          <div class="form-tip">提示: -1表示列表的最后一个元素</div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLRange" :icon="Search">获取范围</el-button>
          <el-button @click="resetRangeForm" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
      <div v-if="lrangeResult.length > 0 || lrangeResultEmpty" class="result-box">
        <div class="result-header">
          <h4>结果:</h4>
          <el-button type="text" @click="copyRangeResult" :icon="CopyDocument">复制</el-button>
        </div>
        <el-alert
          v-if="lrangeResult.length === 0 && lrangeResultEmpty"
          title="列表为空或不存在"
          type="warning"
          :closable="false"
          show-icon
        />
        <el-table 
          v-else 
          :data="lrangeResultArray" 
          stripe 
          border 
          style="width: 100%"
          max-height="300"
        >
          <el-table-column prop="index" label="索引" width="100" />
          <el-table-column prop="value" label="值" />
        </el-table>
      </div>
    </el-card>

    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><Delete /></el-icon> 删除列表</span>
        </div>
      </template>
      <el-form :model="deleteForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="deleteForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="handleDelete" :icon="Delete">删除</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Remove, Search, Refresh, Delete, List, CopyDocument } from '@element-plus/icons-vue'
import { lPush, rPush, lPop, rPop, lRange, del } from '../api/redis'

const lpushForm = reactive({
  key: '',
  value: ''
})

const lpopForm = reactive({
  key: ''
})

const lrangeForm = reactive({
  key: '',
  start: 0,
  end: -1
})

const deleteForm = reactive({
  key: ''
})

const popResult = ref('')
const lrangeResult = ref<string[]>([])
const lrangeResultEmpty = ref(false)

// 将列表结果转换为表格数据
const lrangeResultArray = computed(() => {
  return lrangeResult.value.map((value, index) => ({
    index: lrangeForm.start + index,
    value
  }))
})

const handleLPush = async () => {
  if (!lpushForm.key || !lpushForm.value) {
    ElMessage.warning('请输入键名和值')
    return
  }
  
  try {
    const response = await lPush(lpushForm.key, [lpushForm.value])
    if (response.data.success) {
      ElMessage.success(response.data.message || '左侧添加成功')
      resetPushForm()
    } else {
      ElMessage.error(response.data.message || '添加失败')
    }
  } catch (error: any) {
    console.error('LPUSH error:', error)
    ElMessage.error(error.response?.data?.message || error.message || '添加失败')
  }
}

const handleRPush = async () => {
  if (!lpushForm.key || !lpushForm.value) {
    ElMessage.warning('请输入键名和值')
    return
  }
  
  try {
    const response = await rPush(lpushForm.key, [lpushForm.value])
    if (response.data.success) {
      ElMessage.success(response.data.message || '右侧添加成功')
      resetPushForm()
    } else {
      ElMessage.error(response.data.message || '添加失败')
    }
  } catch (error: any) {
    console.error('RPUSH error:', error)
    ElMessage.error(error.response?.data?.message || error.message || '添加失败')
  }
}

const handleLPop = async () => {
  if (!lpopForm.key) {
    ElMessage.warning('请输入键名')
    return
  }
  
  try {
    const response = await lPop(lpopForm.key)
    if (response.data.success) {
      popResult.value = response.data.data
      if (popResult.value === null) {
        ElMessage.warning(response.data.message || '列表为空或不存在')
      } else {
        ElMessage.success(response.data.message || '左侧移除成功')
      }
    } else {
      ElMessage.error(response.data.message || '移除失败')
      popResult.value = ''
    }
  } catch (error: any) {
    console.error('LPOP error:', error)
    ElMessage.error(error.response?.data?.message || error.message || '移除失败')
    popResult.value = ''
  }
}

const handleRPop = async () => {
  if (!lpopForm.key) {
    ElMessage.warning('请输入键名')
    return
  }
  
  try {
    const response = await rPop(lpopForm.key)
    if (response.data.success) {
      popResult.value = response.data.data
      if (popResult.value === null) {
        ElMessage.warning(response.data.message || '列表为空或不存在')
      } else {
        ElMessage.success(response.data.message || '右侧移除成功')
      }
    } else {
      ElMessage.error(response.data.message || '移除失败')
      popResult.value = ''
    }
  } catch (error: any) {
    console.error('RPOP error:', error)
    ElMessage.error(error.response?.data?.message || error.message || '移除失败')
    popResult.value = ''
  }
}

const handleLRange = async () => {
  if (!lrangeForm.key) {
    ElMessage.warning('请输入键名')
    return
  }
  
  try {
    const response = await lRange(lrangeForm.key, lrangeForm.start, lrangeForm.end)
    // 修复：从response.data.list获取列表数据
    if (response.data.success) {
      lrangeResult.value = response.data.list || []
      lrangeResultEmpty.value = true
      
      if (lrangeResult.value.length === 0) {
        ElMessage.warning('列表为空或不存在')
      } else {
        ElMessage.success(`获取成功，共 ${lrangeResult.value.length} 个元素`)
      }
    } else {
      ElMessage.error(response.data.error || '获取失败')
      lrangeResult.value = []
      lrangeResultEmpty.value = false
    }
  } catch (error: any) {
    console.error('LRANGE error:', error)
    ElMessage.error(error.response?.data?.error || error.message || '获取失败')
    lrangeResult.value = []
    lrangeResultEmpty.value = false
  }
}

const handleDelete = async () => {
  if (!deleteForm.key) {
    ElMessage.warning('请输入键名')
    return
  }
  
  try {
    await del(deleteForm.key)
    ElMessage.success('删除成功')
    deleteForm.key = ''
    
    // 如果当前正在查询的键被删除，清空结果
    if (lpopForm.key === deleteForm.key) {
      popResult.value = ''
    }
    if (lrangeForm.key === deleteForm.key) {
      lrangeResult.value = []
      lrangeResultEmpty.value = false
    }
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

const resetPushForm = () => {
  lpushForm.key = ''
  lpushForm.value = ''
}

const resetPopForm = () => {
  lpopForm.key = ''
  popResult.value = ''
}

const resetRangeForm = () => {
  lrangeForm.key = ''
  lrangeForm.start = 0
  lrangeForm.end = -1
  lrangeResult.value = []
  lrangeResultEmpty.value = false
}

const copyPopResult = () => {
  if (popResult.value) {
    navigator.clipboard.writeText(popResult.value)
    ElMessage.success('已复制到剪贴板')
  }
}

const copyRangeResult = () => {
  if (lrangeResult.value.length > 0) {
    navigator.clipboard.writeText(JSON.stringify(lrangeResult.value, null, 2))
    ElMessage.success('已复制到剪贴板')
  }
}
</script>

<style scoped>
.list-operations {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 20px;
}

.operation-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.operation-card:hover {
  transform: translateY(-5px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.card-header .el-icon {
  margin-right: 5px;
}

.result-box {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.result-header h4 {
  margin: 0;
}

pre {
  white-space: pre-wrap;
  word-break: break-all;
  margin: 0;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-family: 'Courier New', Courier, monospace;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .list-operations {
    grid-template-columns: 1fr;
  }
}
</style>